package handler

import (
	"fmt"
	"go_chat/logger"
	"go_chat/model"
	"net"
	"strings"
)

func ProcessInfo(conn net.Conn, msgQueue chan string){
	buf := make([]byte, 1024)
	defer func(conn net.Conn){
		// 退出是删除映射表中得ip
		addr :=  conn.RemoteAddr().String()
		fmt.Printf("client %s already exit! \n", addr)
		delete(model.OnlineConns, addr)
		conn.Close()
	}(conn)
	for{
		// 将连接信息读入到buf
		numOfBytes, err := conn.Read(buf)
		if err != nil {
			break
		}
		if numOfBytes != 0 {
			// 将发送来得消息写入到消息队列
			message := string(buf[0 : numOfBytes])
			msgQueue <- message
		}
	}
}

// 解析消息返回
func DoProcessMessage(msg string){
	// 发送得消息需要格式如下: ip#消息
	contents := strings.Split(msg, "#")
	if len(contents) > 1 {
		addr := contents[0]
		sendMessage := strings.Join(contents[1:], "")
		addr = strings.Trim(addr, " ")
		if conn, ok := model.OnlineConns[addr]; ok {
			_, err := conn.Write([]byte(sendMessage))
			if err != nil {
				errStr := fmt.Sprintf("online connect(%s) send failure: %s\n", addr, err.Error())
				logger.GetLogger().Println(errStr)
				fmt.Println(errStr)
			}
		}
	}else{
		// 使用当前ip*list可以查询到socket上连接的所有的ip
		contents := strings.Split(msg, "*")
		if len(contents) > 0 && strings.ToUpper(contents[1]) == "LIST" {
			var ips = ""
			for ip := range model.OnlineConns {
				ips += ip + "\t"
			}
			if conn, ok := model.OnlineConns[contents[0]]; ok {
				conn.Write([]byte(ips))
			}
		}
	}
}